'''网络图片上传线程.

线程任务为上传一批图片,指定域名,分类,标签,每上传一个图片返回一次状态表.
保存上传结果到WebPicDatabase.json

初始化参数self._uploaders是可用的上传器列表,从from _Uploader import *
导入的所有上传器都可用.
self._domains是可用域名表,用于被App类访问,渲染网页中的可用域名

线程参数data{}:
files:[上传文件名]
domain:上传的域名
type:分类,空字符串则为'default'
tags:[标签表],可以为空

状态表self._status['status']={'msg': 上传情况}
'''

import sys
import os

from BaseThread import BaseThread
## 导入classes文件夹
sys.path.append(os.path.join(sys.path[0], r'classes'))
from _Uploader import *
from _MyDatabase import MyDatabase

class WebPicUploadThread(BaseThread):

  def __init__(self):
    BaseThread.__init__(self)
    self._uploaders = [
      imgurl_org_Uploader(),
      sm_ms_Uploader(),
      png8_com_Uploader(),
      img_vim_cn_com_Uploader(),
      niupic_com_Uploader()
    ]
    self._domains = [x._domain for x in self._uploaders]
    self._db = MyDatabase(os.path.join(
      sys.path[0],
      'database', 'WebPicDatabase.json')
    )
    self._status['status']['msg'] = '未开始上传'
    return

  ## 处理上传的data,返回元组(files(列表),domain(字符串),_type(字符串),
  ## tags(列表)
  def _handleData(self, data):
    files = [x.strip() for x in data['files'].split('\n')]
    files = list(filter(lambda x:len(x) > 0, files))
    domain = data['domain'].strip()
    _type = data['type'].strip()
    if not _type:
      _type = 'default'
    tags = [x.strip() for x in data['tags'].split(',')]  
    tags = list(filter(lambda x:len(x) > 0, tags))
    return (files, domain, _type, tags)
    
  def _thread(self, data):
    files, domain, _type, tags = self._handleData(data)
    uploader = None
    for _uploader in self._uploaders:
      if _uploader._domain == domain:
        uploader = _uploader
        break
    if not uploader:
      raise Exception(f'域名{domain}不存在!')
      return
    self._db = MyDatabase(os.path.join(
      sys.path[0],
      'database', 'WebPicDatabase.json')
    )
    self._status['status']['msg'] = '开始上传图片'
    total = len(files)
    failed = 0
    succeeded = 0
    for f in files:
      self._status['status']['msg'] = f'上传中,成功{succeeded},失败{failed}'
      result = uploader.upload(f, tags, _type)
      if result:
        succeeded += 1
        if 'type' in result:
          del result['type']
        self._db.add(result, _type)
      else:
        failed += 1
    if succeeded > 0:
      self._db.save()
    return f'上传完成,成功{succeeded},失败{failed}'